import config from '@/config'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import { logout, getMiniAppUserInfo,wxMiniLogin } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const baseUrl = config.baseUrl

const user = {
  state: {
    token: getToken(),
    name: storage.get(constant.name),
    avatar: storage.get(constant.avatar),
    roles: storage.get(constant.roles),
    permissions: storage.get(constant.permissions)
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
      storage.set(constant.name, name)
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
      storage.set(constant.avatar, avatar)
    },
  },

  actions: {
	//快捷登录
	WxMiniLogin({ commit }, loginBody) {
	  return new Promise((resolve, reject) => {
	    wxMiniLogin(loginBody).then(res => {
	      setToken(res.data.token)
	      commit('SET_TOKEN', res.data.token)
	      resolve()
	    }).catch(error => {
	      reject(error)
	    })
	  })
	},

    // 获取用户信息
    GetMiniAppUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getMiniAppUserInfo().then(res => {
          const user = res.data
          const avatar = (user == null || user.avatar == "" || user.avatar == null) ? require("@/static/images/profile.jpg") :  user.avatar
          const nickName = (user == null || user.nickName == "" || user.nickName == null) ? "" : user.nickName
          commit('SET_NAME', nickName)
          commit('SET_AVATAR', avatar)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          storage.clean()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user
